package com.iqunxing.redis.redisInAction.ch08.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.google.common.base.Preconditions;
import com.iqunxing.redis.redisInAction.ch08.po.User;
import com.iqunxing.redis.redisInAction.ch08.util.Lock;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private Lock lock;

    @Override
    public Long createUser(String loginName, String name) {
        Preconditions.checkNotNull(loginName, "登陆名不能为空");
        Preconditions.checkNotNull(name, "姓名不能为空");
        loginName = loginName.toLowerCase();
        Long userId = null;
        String lockId = null;
        String lockName = "userlock:" + loginName;
        try {
            lockId = lock.acquireLock(lockName);
            Preconditions.checkNotNull(lockId, "获取锁失败，创建用户失败");
            boolean exists = redisTemplate.boundHashOps("users:").hasKey(loginName);
            Preconditions.checkArgument(!exists, "该用户已经存在");
            userId = redisTemplate.boundHashOps("id").increment("userId", 1L);
            redisTemplate.boundHashOps("users").put(loginName, userId);
            User user = new User(userId, loginName, name);
            redisTemplate.boundHashOps("user").put(userId, user);
        } finally {
            lock.releaseLock(lockName, lockId);
        }
        return userId;
    }

}
